<?php
// +----------------------------------------------------------------------
// | VueAdmin框架[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://www.vueadmin.org
// +----------------------------------------------------------------------
// | VueAdmin承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: sept <917088650@qq.com>，开发者QQ群：63131383
// +----------------------------------------------------------------------

namespace app\system\controller;

use app\lib\Auth\Auth;
use app\lib\exception\ApiException;
use app\lib\exception\ForbiddenException;
use app\lib\requests\Response;
use app\lib\returnCode\Code;
use app\lib\returnCode\Msg;
use app\system\model\AdminRole as RoleModel;
use app\system\model\AdminRole;
use app\system\validate\IDMustBePostiveInt;
use app\system\validate\RoleNew;

class Role extends Base
{

    /**
     * 角色管理
     * @author sept <917088650@qq.com>
     * @return \think\response\Json
     */
    public function view()
    {
        $limit = input('param.limit/d', 15);
        $fields = $this->request->get('fields','*');

        $role_model = new RoleModel();

        $data_info = $role_model->field($fields)->paginate($limit);

        if ($data_info->isEmpty()) {
            throw new ApiException(Code::NO_FIND_RELATE_RECORD,Msg::NO_FIND_RELATE_RECORD);
        }

        return Response::success($data_info);
    }

    /**
     * 添加角色
     * @author sept <917088650@qq.com>
     * @return mixed
     */
    public function add()
    {
        $data = $this->request->post();

        (new RoleNew())->goCheck();

        RoleModel::create($data);

        return Response::success();
    }

    /**
     * 修改角色
     * @param int $id
     * @author sept <917088650@qq.com>
     * @return mixed
     */
    public function edit($id = 0)
    {

        (new IDMustBePostiveInt())->goCheck();
        (new RoleNew())->goCheck();

        $data = $this->request->post();
        // 当前登陆用户不可更改自己的分组角色
        if (Auth::user()->role_id == $id) {
            throw new ApiException(Code::SYSTEM_DELETE_ADMINI_RULE,Msg::SYSTEM_DELETE_ADMINI_RULE);
        }

        $role_model = new RoleModel();
        $role_model->storage($data,$id);

        // 更新权限缓存
        cache('role_auth_'.$id, $data['auth']);

        return Response::success();
    }

    /**
     * 删除角色
     * @param int $id
     * @author sept <917088650@qq.com>
     * @return mixed
     */
    public function delete($ids = 0)
    {
        $model = new RoleModel();
        $model->del($ids);
        return Response::success();
    }
}